import axios from 'axios'
import { ElMessage } from 'element-plus'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 自动携带JWT token
    const token = localStorage.getItem('access');
    if (token) {
      config.headers['Authorization'] = 'Bearer ' + token;
    }
    if (['post', 'put'].includes(config.method)) {
      const user = JSON.parse(localStorage.getItem('user') || 'null');
      if (user && user.id) {
        if (config.data && typeof config.data === 'object') {
          config.data.created_by = user.id;
        }
      }
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    // 处理401未授权错误，尝试刷新token
    if (error.response?.status === 401) {
      const refreshToken = localStorage.getItem('refresh');
      if (refreshToken) {
        // 尝试刷新token
        return api.post('/users/token/refresh/', { refresh: refreshToken })
          .then(response => {
            if (response.access) {
              localStorage.setItem('access', response.access);
              // 重试原始请求
              const originalRequest = error.config;
              originalRequest.headers['Authorization'] = 'Bearer ' + response.access;
              return api(originalRequest);
            }
          })
          .catch(refreshError => {
            // 刷新失败，清除本地存储并跳转到登录页
            localStorage.removeItem('access');
            localStorage.removeItem('refresh');
            localStorage.removeItem('user');
            window.location.href = '/login';
            return Promise.reject(refreshError);
          });
      } else {
        // 没有refresh token，跳转到登录页
        localStorage.removeItem('access');
        localStorage.removeItem('refresh');
        localStorage.removeItem('user');
        window.location.href = '/login';
      }
    }
    
    const message = error.response?.data?.message || error.message || '请求失败'
    ElMessage.error(message)
    return Promise.reject(error)
  }
)

// API接口封装
export const environmentAPI = {
  // 获取环境列表
  getList: (params) => api.get('/environments/', { params }),
  // 获取环境详情
  getDetail: (id) => api.get(`/environments/${id}/`),
  // 创建环境
  create: (data) => api.post('/environments/', data),
  // 更新环境
  update: (id, data) => api.put(`/environments/${id}/`, data),
  // 删除环境
  delete: (id) => api.delete(`/environments/${id}/`),
  // 验证YAML配置
  validateYaml: (data) => api.post('/environments/validate_yaml/', data),
  // 格式化YAML配置
  formatYaml: (data) => api.post('/environments/format_yaml/', data)
}

export const testCaseAPI = {
  // 获取测试用例列表
  getList: (params) => api.get('/testcases/', { params }),
  // 获取测试用例详情
  getDetail: (id) => api.get(`/testcases/${id}/`),
  // 创建测试用例
  create: (data) => api.post('/testcases/', data),
  // 更新测试用例
  update: (id, data) => api.put(`/testcases/${id}/`, data),
  // 删除测试用例
  delete: (id) => api.delete(`/testcases/${id}/`),
  // 执行测试用例
  execute: (id) => api.post(`/testcases/${id}/execute/`),
  // 验证YAML配置
  validateYaml: (id) => api.post(`/testcases/${id}/validate_yaml/`)
}

export const executionAPI = {
  // 获取执行记录列表
  getList: (params) => api.get('/executions/', { params }),
  // 获取执行记录详情
  getDetail: (id) => api.get(`/executions/${id}/`),
  // 重试执行
  retry: (id) => api.post(`/executions/${id}/retry/`)
}

export const reportAPI = {
  // 获取报告列表
  getList: (params) => api.get('/reports/', { params }),
  // 获取报告详情
  getDetail: (id) => api.get(`/reports/${id}/`),
  // 生成报告
  generate: (data) => api.post('/reports/generate_report/', data)
}

export const dailyLogAPI = {
  // 获取日志列表
  getList: (params) => api.get('/daily/logs/', { params }),
  // 获取日志详情
  getDetail: (id) => api.get(`/daily/logs/${id}/`),
  // 创建日志
  create: (data) => api.post('/daily/logs/', data),
  // 更新日志
  update: (id, data) => api.patch(`/daily/logs/${id}/`, data),
  // 删除日志
  delete: (id) => api.delete(`/daily/logs/${id}/`)
}

// 登录接口
export const login = async (data) => {
  const response = await api.post('/users/login/', data);
  if (response && response.user) {
    localStorage.setItem('user', JSON.stringify(response.user));
    // 存储JWT token
    if (response.access) {
      localStorage.setItem('access', response.access);
    }
    if (response.refresh) {
      localStorage.setItem('refresh', response.refresh);
    }
  }
  return response;
};

// 注册接口
export const register = async (data) => {
  const response = await api.post('/users/register/', data);
  return response;
};

// 登出接口
export const logout = () => {
  localStorage.removeItem('access');
  localStorage.removeItem('refresh');
  localStorage.removeItem('user');
};

export default api 